package com.iptv.grape.video;

import android.os.Handler;
import android.os.Message;
import android.view.View;

import com.iptv.grape.BaseActivity;
import com.iptv.grape.R;
import com.iptv.grape.bu.AppConfig;
import com.iptv.grape.bu.GrapeContext;
import com.iptv.grape.bu.imp.QuitBackMode;
import com.iptv.grape.bu.imp.QuitFullScreen;
import com.iptv.grape.bu.process.VodPlayProcess;
import com.iptv.grape.domain.AssetPlayData;
import com.iptv.grape.event.EventArgs;
import com.iptv.grape.event.data.TimeLiveData;
import com.iptv.grape.event.data.VodData;
import com.iptv.grape.event.msg.EsObj;
import com.iptv.grape.event.msg.PlayContinuouslyMsg;
import com.iptv.grape.event.msg.SubAsset;
import com.iptv.grape.util.AppConstant;
import com.iptv.grape.util.AppLog;
import com.iptv.grape.util.WebViewUtils;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class DefXMediaPlayerEventListener implements IPlayerListener {

    private BaseActivity activity;
    private VodPlayProcess vodPlayProcess;
    private List<IProgressListener> progressListeners = new ArrayList<IProgressListener>();
    private List<IPlayCompletion> playCompletionListeners = new ArrayList<IPlayCompletion>();

    public VodPlayProcess getVodPlayProcess() {
        return vodPlayProcess;
    }

    public void setVodPlayProcess(VodPlayProcess vodPlayProcess) {
        this.vodPlayProcess = vodPlayProcess;
    }

    // 添加事件监听者
    public void addProgressListener(IProgressListener progressListener){
        progressListeners.add(progressListener);
    }
    // 移除事件监听者
    public void removeProgressListener(IProgressListener progressListener){
        if(!progressListeners.isEmpty()){
            progressListeners.remove(progressListener);
        }
    }

    // 添加事件监听者
    public void addPlayCompletionListener(IPlayCompletion playCompletion){
        playCompletionListeners.add(playCompletion);
    }
    // 移除事件监听者
    public void removePlayCompletionListener(IPlayCompletion playCompletion){
        if(!playCompletionListeners.isEmpty()){
            playCompletionListeners.remove(playCompletion);
        }

    }

    public DefXMediaPlayerEventListener(BaseActivity activity){
        this.activity = activity;
    }

    public BaseActivity getActivity() {
        return activity;
    }

    // 播放事件
    @Override
    public void onPlaying() {
        AppLog.getCurLog().out("XMediaPlayer -------- 开始播放");
        //this.activity.findViewById(R.id.pause_layout).setVisibility(View.GONE);
        this.activity.hideAdImg();
        if (GrapeContext.curGrapeContext().getCurPlayType().equals("Vod")) {
            VodData vodData = VodData.getCurVodData();
            if(vodData != null){
                vodData.setVodTime(GrapeContext.curGrapeContext().getCurMediaPlayer().getDuration());
                vodData.setVodOperateType("0");
                EventBus.getDefault().post(new EventArgs(AppConstant.Vod, AppConstant.DataAcquisition, vodData));
            }

        }
        if (GrapeContext.curGrapeContext().getCurPlayType().equals("Live") && GrapeContext.curGrapeContext().curLiveType().equals("Time")) {
            AppLog.getCurLog().out("时移开始");
            TimeLiveData timeLiveData = TimeLiveData.getCurTimeLiveData();
            if(timeLiveData != null){
                timeLiveData.setState("0");
                EventBus.getDefault().post(new EventArgs(AppConstant.Time, AppConstant.DataAcquisition, timeLiveData));
            }
        }
    }

    // 播放暂停事件
    @Override
    public void onPlayPause() {
        AppLog.getCurLog().out("XMediaPlayer -------- 播放暂停");
        //this.activity.findViewById(R.id.pause_layout).setVisibility(View.VISIBLE);
        this.activity.showAdImg();
        if (GrapeContext.curGrapeContext().getCurPlayType().equals("Vod")) {
            VodData vodData = VodData.getCurVodData();
            if(vodData != null){
                vodData.setVodOperateType("3");
                EventBus.getDefault().post(new EventArgs(AppConstant.Vod, AppConstant.DataAcquisition, vodData));
            }
        }
    }

    // 停止播放事件
    @Override
    public void onStop(int speed) {
        if( GrapeContext.curGrapeContext().getCurPlayType().equals("Vod")){
            if(GrapeContext.curGrapeContext().getCurPlayVod() != null){
                AppLog.getCurLog().out(speed);
                GrapeContext.curGrapeContext().getCurPlayVod().setCurLastPlayTime(speed);
                GrapeContext.curGrapeContext().getCurPlayVod().setLastPlayDate(new Date());
                GrapeContext.curGrapeContext().getAssetPlayDataList().serializeToFile();
            }
            VodData vodData = VodData.getCurVodData();
            if(vodData != null){
                vodData.setState("1");
                EventBus.getDefault().post(new EventArgs(AppConstant.Vod, AppConstant.DataAcquisition, vodData));
            }
        }
        if (GrapeContext.curGrapeContext().getCurPlayType().equals("Live") && GrapeContext.curGrapeContext().curLiveType().equals("Time")) {
            AppLog.getCurLog().out("时移停止");
            TimeLiveData timeLiveData = TimeLiveData.getCurTimeLiveData();
            if(timeLiveData != null){
                timeLiveData.setState("1");
                EventBus.getDefault().post(new EventArgs(AppConstant.Time, AppConstant.DataAcquisition, timeLiveData));
            }
        }

    }

    // 播放错误事件
    @Override
    public void onError() {
        AppLog.getCurLog().out("XMediaPlayer -------- 播放错误");
    }

    // 播放进度 报告事件
    // 直播无进度报告
    @Override
    public void onProgress(int speed) {
        //AppLog.getCurLog().out("XMediaPlayer -------- onProgress");
        if(!progressListeners.isEmpty()){
            for (IProgressListener listeners:progressListeners) {
                listeners.onProgress(speed);
            }
        }
    }

    // 进入全屏
    @Override
    public void onIntoFullScreen() {
        AppLog.getCurLog().out("XMediaPlayer -------- 进入全屏");
    }

    // 退出全屏
    @Override
    public void onQuitFullScreen() {
        AppLog.getCurLog().out("XMediaPlayer -------- 退出全屏");
    }

    // 播放完成
    @Override
    public void playCompletion(){
        AppLog.getCurLog().out("XMediaPlayer -------- 播放完成");
        if(!playCompletionListeners.isEmpty()){
            if(!progressListeners.isEmpty()){
                for (IPlayCompletion listeners:playCompletionListeners) {
                    listeners.playCompletion();
                }
            }
        }
        try {
            if (GrapeContext.curGrapeContext().getCurPlayType().equals("Vod")) {

                boolean isNeedQuitFullScreen = false;
                AssetPlayData curAssetPlayData = GrapeContext.curGrapeContext().getCurPlayVod();
                List<EsObj> subAssets = curAssetPlayData.getSubList();
                int curIndex = curAssetPlayData.getCurIndex();
                if (curAssetPlayData.getCurIndex() + 1 >= subAssets.size()) {
                    curIndex = 0;
                    // 跳到第一集则需要退出全屏
                    isNeedQuitFullScreen = true;
                } else {
                    curIndex++;
                }
                AppLog.getCurLog().out("curIndex=" + curIndex);
                SubAsset subAsset = subAssets.get(curIndex).getSource();
                curAssetPlayData.setCurIndex(curIndex);
                curAssetPlayData.setPlayUrl(subAsset.getPlayUrl());
                curAssetPlayData.setSubAssetID(subAsset.getSubAssetID());
                GrapeContext.curGrapeContext().setCurPlayVod(curAssetPlayData);

                if(curAssetPlayData.getType().equals("TVSeries")){
                    PlayContinuouslyMsg msg = new PlayContinuouslyMsg(subAsset.getSubAssetID());
                    WebViewUtils.sentKeyMessageToWebView(msg.toJson(),activity.getBridgeWebView());
                }

                GrapeContext.curGrapeContext().getCurMediaPlayer().seekToVod(GrapeContext.curGrapeContext().getCurPlayVod().getCurLastPlayTime());
                GrapeContext.curGrapeContext().getCurMediaPlayer().play(GrapeContext.curGrapeContext().getCurActivity(), GrapeContext.curGrapeContext().getCurPlayVod().getPlayUrl());
                GrapeContext.curGrapeContext().setPlaying(true);
                GrapeContext.curGrapeContext().setCurPlayType("Vod");

                if(isNeedQuitFullScreen && GrapeContext.curGrapeContext().isFullScreen()){
                    // 整个电影或者电视剧需要退出全屏
                    QuitFullScreen.quitFullScreen(GrapeContext.curGrapeContext().getCurActivity());
                }
//
//                this.activity.runOnUiThread(new Runnable() {
//
//                    @Override
//                    public void run() {
//                        try {
//
//                        }
//                        catch (Exception e){
//                            e.printStackTrace();
//                            AppLog.getCurLog().out("错误" + e.getMessage());
//                        }
//
//                    }
//                });


            }
            else {

                AppLog.getCurLog().out("-----------rePlay---------------");
                GrapeContext.curGrapeContext().getCurMediaPlayer().rePlay(GrapeContext.curGrapeContext().getCurActivity());
                //GrapeContext.curGrapeContext().getCurMediaPlayer()

            }

        }
        catch (Exception e){
            e.printStackTrace();
            AppLog.getCurLog().out("错误" + e.getMessage());

        }
    }


    // 播放完成
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 90:
                    GrapeContext.curGrapeContext().getCurMediaPlayer().seekToVod(GrapeContext.curGrapeContext().getCurPlayVod().getCurLastPlayTime());
                    GrapeContext.curGrapeContext().getCurMediaPlayer().play(GrapeContext.curGrapeContext().getCurActivity(), GrapeContext.curGrapeContext().getCurPlayVod().getPlayUrl());
                    GrapeContext.curGrapeContext().setPlaying(true);
                    GrapeContext.curGrapeContext().setCurPlayType("Vod");
                    break;
            }
        }
    };
}
